package com.it.park.controller.user;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.it.park.client.service.BookService;
import com.it.park.common.SessionUtil;
import com.it.park.constant.Constant;
import com.it.park.model.Book;
import com.it.park.rms.client.model.User;
import com.it.park.util.file.FileUtil;
import com.it.park.util.image.ImageUtil;

@Controller
@RequestMapping("/user/book")
public class UserBookController {
	private String rootPath=Constant.USER_PATH;
	
	@Autowired
	private BookService bookService;
	
	@RequestMapping("bookList")
	public String bookList(HttpServletRequest request,HttpSession session){
		User user = SessionUtil.getSessionUser(session);
		List<Book> books = bookService.selectByUserId(user.getId());
		request.setAttribute("books", books);
		return rootPath+"resourcefile/bookList";
	}
	
	@RequestMapping("saveBook")
	public String saveBook(@RequestParam("file") MultipartFile[] file,Book book,HttpServletRequest request,HttpSession session){
		if(file != null){
			try {
				User user = SessionUtil.getSessionUser(session);
				String bookUrl = null;
				String imgUrl = null;
				if(file[0] != null){
					imgUrl = FileUtil.getImgFilePath(request,user.getUserName(),file[0].getOriginalFilename());
					file[0].transferTo(new File(imgUrl));
				}
				if(file[1] != null){
					bookUrl = FileUtil.getBookFilePath(request,user.getUserName(),file[1].getOriginalFilename());
					file[1].transferTo(new File(bookUrl));
				}
				book.setUserId(user.getId());
				book.setClickRate(0);
				book.setBookUrl(bookUrl);
				book.setImgUrl(imgUrl);
				book.setCreateDate(new Date());
				bookService.insertSelective(book);	
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "redirect:bookList";
	}
	
	/**
	 *显示图片
	 */
	@RequestMapping("showImgShow")
	public void showPicture(Integer id,HttpServletResponse response) throws IOException{
		Book book =	bookService.selectByPrimaryKey(id);
		ImageUtil.showPicture(book.getImgUrl(),response);
	}
	
}
